import { _decorator, Node } from 'cc'
import { DIRECTION_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_NAME_ENUM } from '../enums'
import { EntityMgr } from '../base/EntityMgr'
import EventMgr from '../runtime/EventMgr'
import { DoorStateMachine } from './DoorStateMachine'
import DataMgr from '../runtime/DataMgr'
import { IEntity } from '../levels'
const { ccclass, property } = _decorator
/** 木骷髅管理器 实际创建木骷髅的逻辑 */
// 紧记 地图是以左上角为原点，向下y轴是负数，往左x轴是正数的坐标图
@ccclass('DoorMgr')
export class DoorMgr extends EntityMgr {
  async init(initData: IEntity) {
    // 添加状态机
    this.fsm = this.addComponent(DoorStateMachine)
    await this.fsm.init() // 初始化状态机参数

    // 使用父类的init方法
    super.init(initData)

    EventMgr.Instance.on(EVENT_NAME_ENUM.OPEN_DOOR, this.handleOpenDoor, this) // 监听门打开事件
  }

  handleOpenDoor(enemyId: string) {
    const isEnemyAllDead = DataMgr.Instance.enemies.every(enemy => enemy.state === ENTITY_STATE_ENUM.DEATH)
    if (isEnemyAllDead) {
      const enemy = DataMgr.Instance.enemies.find(enemy => enemy.id === enemyId)
      if (enemy) {
        console.log(
          'enemy.fsm.animationComponent.defaultClip.duration',
          enemy.fsm.animationComponent.defaultClip.duration,
        )
        this.scheduleOnce(() => {
          this.state = ENTITY_STATE_ENUM.DEATH
        }, enemy.fsm.animationComponent.defaultClip.duration - 0.5)
      }
    }
  }

  onDestroy(): void {
    EventMgr.Instance.off(EVENT_NAME_ENUM.OPEN_DOOR, this.handleOpenDoor)
  }
}
